package com.peng.utils;

import com.peng.domain.entity.Menu;
import com.peng.domain.vo.MenuTreeVo;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class SystemConverter {

    private SystemConverter() {
    }


    public static List<MenuTreeVo> buildMenuSelectTree(List<Menu> menus) {
        List<MenuTreeVo> MenuTreeVos = menus.stream()
                .map(new Function<Menu, MenuTreeVo>() {
                    @Override
                    public MenuTreeVo apply(Menu menu) {
                        return new MenuTreeVo(menu.getId(), menu.getMenuName(), menu.getParentId(), null);
                    }
                })
                .collect(Collectors.toList());
        List<MenuTreeVo> options = MenuTreeVos.stream()
                .filter(new Predicate<MenuTreeVo>() {
                    @Override
                    public boolean test(MenuTreeVo menuTreeVo) {
                        return menuTreeVo.getParentId().equals(0L);
                    }
                })
                .map(new Function<MenuTreeVo, MenuTreeVo>() {
                    @Override
                    public MenuTreeVo apply(MenuTreeVo menuTreeVo) {
                        return menuTreeVo.setChildren(getChildList(MenuTreeVos, menuTreeVo));
                    }
                })
                .collect(Collectors.toList());


        return options;
    }


    /**
     * 得到子节点列表
     */
    private static List<MenuTreeVo> getChildList(List<MenuTreeVo> list, MenuTreeVo option) {
        List<MenuTreeVo> options = list.stream()
                .filter(new Predicate<MenuTreeVo>() {
                    @Override
                    public boolean test(MenuTreeVo menuTreeVo) {
                        return Objects.equals(menuTreeVo.getParentId(), option.getId());
                    }
                })
                .map(new Function<MenuTreeVo, MenuTreeVo>() {
                    @Override
                    public MenuTreeVo apply(MenuTreeVo menuTreeVo) {
                        return menuTreeVo.setChildren(getChildList(list, menuTreeVo));
                    }
                })
                .collect(Collectors.toList());
        return options;

    }
}